// quick4.hxx


#ifndef _BLOGS_QUICK4
#define _BLOGS_QUICK4


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"
#include "std_out.hxx"
#include "std_random.hxx"


namespace blogs
{


class Quick4
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __sort__(Array<_T> & a, int lo, int hi)
    {
        if (hi <= lo) return;
        _T v = a[lo];
        int i = lo+1, j = hi, p = lo+1, q = hi;
        while (true) {
            while (i <= j) {
                int cmp = a[i].compare_to(v);
                if (cmp  > 0) break;
                if (cmp == 0) __exch__(a, p++, i);
                ++i;
            }
            while (i < j) {
                int cmp = a[j].compare_to(v);
                if (cmp  < 0) break;
                if (cmp == 0) __exch__(a, q--, j);
                --j;
            }
            if (i >= j) break;
            __exch__(a, i++, j--);
        }
        j = i-1;
        for (int k = lo; k < p; ++k) __exch__(a, k, j--);
        for (int k = hi; k > q; --k) __exch__(a, k, i++);
        __sort__(a, lo, j);
        __sort__(a, i, hi);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __exch__(Array<_T> & a, int i, int j)
    {
        _T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        Std_Random::shuffle(a);
        __sort__(a, 0, a.size()-1);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

